{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "dcgan.ipynb",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.2"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "_jQ1tEQCxwRx"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "V_sgB_5dx1f1",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "rF2x3qooyBTI"
      },
      "source": [
        "# 深度卷积生成对抗网络"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0TD5ZrvEMbhZ"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://tensorflow.google.cn/tutorials/generative/dcgan\">\n",
        "    <img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\" />\n",
        "    在 tensorFlow.google.cn 上查看</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/zh-cn/tutorials/generative/dcgan.ipynb\">\n",
        "    <img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\" />\n",
        "    在 Google Colab 中运行</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/zh-cn/tutorials/generative/dcgan.ipynb\">\n",
        "    <img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\" />\n",
        "    在 GitHub 上查看源代码</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/zh-cn/tutorials/generative/dcgan.ipynb\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\" />下载 notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "M0gHG-LEgLZx"
      },
      "source": [
        "Note: 我们的 TensorFlow 社区翻译了这些文档。因为社区翻译是尽力而为， 所以无法保证它们是最准确的，并且反映了最新的\n",
        "[官方英文文档](https://www.tensorflow.org/?hl=en)。如果您有改进此翻译的建议， 请提交 pull request 到\n",
        "[tensorflow/docs](https://github.com/tensorflow/docs) GitHub 仓库。要志愿地撰写或者审核译文，请加入\n",
        "[docs-zh-cn@tensorflow.org Google Group](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-zh-cn)。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ITZuApL56Mny"
      },
      "source": [
        "本教程演示了如何使用[深度卷积生成对抗网络](https://arxiv.org/pdf/1511.06434.pdf)（DCGAN）生成手写数字图片。该代码是使用 [Keras Sequential API](https://tensorflow.google.cn/guide/keras) 与 `tf.GradientTape` 训练循环编写的。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2MbKJY38Puy9"
      },
      "source": [
        "## 什么是生成对抗网络？\n",
        "\n",
        "[生成对抗网络](https://arxiv.org/abs/1406.2661)（GANs）是当今计算机科学领域最有趣的想法之一。两个模型通过对抗过程同时训练。一个*生成器*（“艺术家”）学习创造看起来真实的图像，而*判别器*（“艺术评论家”）学习区分真假图像。\n",
        "\n",
        "![生成器和判别器图示](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/images/gan1.png?raw=1)\n",
        "\n",
        "训练过程中，*生成器*在生成逼真图像方面逐渐变强，而*判别器*在辨别这些图像的能力上逐渐变强。当*判别器*不再能够区分真实图片和伪造图片时，训练过程达到平衡。\n",
        "\n",
        "![生成器和判别器图示二](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/images/gan2.png?raw=1)\n",
        "\n",
        "本笔记在 MNIST 数据集上演示了该过程。下方动画展示了当训练了 50 个epoch （全部数据集迭代50次） 时*生成器*所生成的一系列图片。图片从随机噪声开始，随着时间的推移越来越像手写数字。\n",
        "\n",
        "![输出样本](https://tensorflow.google.cn/images/gan/dcgan.gif)\n",
        "\n",
        "要了解关于 GANs 的更多信息，我们建议参阅 MIT的 [深度学习入门](http://introtodeeplearning.com/) 课程。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "e1_Y75QXJS6h"
      },
      "source": [
        "### Import TensorFlow and other libraries"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "J5oue0oqCkZZ",
        "colab": {}
      },
      "source": [
        "from __future__ import absolute_import, division, print_function, unicode_literals"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "g5RstiiB8V-z",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  # %tensorflow_version 只在 Colab 中使用。\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "WZKbyU2-AiY-",
        "colab": {}
      },
      "source": [
        "import tensorflow as tf"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "57FFuKn4gLZ9",
        "colab": {}
      },
      "source": [
        "tf.__version__"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "YzTlj4YdCip_",
        "colab": {}
      },
      "source": [
        "# 用于生成 GIF 图片\n",
        "!pip install imageio"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "YfIk2es3hJEd",
        "colab": {}
      },
      "source": [
        "import glob\n",
        "import imageio\n",
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "import os\n",
        "import PIL\n",
        "from tensorflow.keras import layers\n",
        "import time\n",
        "\n",
        "from IPython import display"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "iYn4MdZnKCey"
      },
      "source": [
        "### 加载和准备数据集\n",
        "\n",
        "您将使用 MNIST 数据集来训练生成器和判别器。生成器将生成类似于 MNIST 数据集的手写数字。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "a4fYMGxGhrna",
        "colab": {}
      },
      "source": [
        "(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "NFC2ghIdiZYE",
        "colab": {}
      },
      "source": [
        "train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')\n",
        "train_images = (train_images - 127.5) / 127.5 # 将图片标准化到 [-1, 1] 区间内"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "S4PIDhoDLbsZ",
        "colab": {}
      },
      "source": [
        "BUFFER_SIZE = 60000\n",
        "BATCH_SIZE = 256"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "-yKCCQOoJ7cn",
        "colab": {}
      },
      "source": [
        "# 批量化和打乱数据\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "THY-sZMiQ4UV"
      },
      "source": [
        "## 创建模型\n",
        "\n",
        "生成器和判别器均使用 [Keras Sequential API](https://tensorflow.google.cn/guide/keras#sequential_model) 定义。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-tEyxE-GMC48"
      },
      "source": [
        "### 生成器\n",
        "\n",
        "生成器使用 `tf.keras.layers.Conv2DTranspose` （上采样）层来从种子（随机噪声）中产生图片。以一个使用该种子作为输入的 `Dense` 层开始，然后多次上采样直到达到所期望的 28x28x1 的图片尺寸。注意除了输出层使用 tanh 之外，其他每层均使用 `tf.keras.layers.LeakyReLU` 作为激活函数。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "6bpTcDqoLWjY",
        "colab": {}
      },
      "source": [
        "def make_generator_model():\n",
        "    model = tf.keras.Sequential()\n",
        "    model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,)))\n",
        "    model.add(layers.BatchNormalization())\n",
        "    model.add(layers.LeakyReLU())\n",
        "\n",
        "    model.add(layers.Reshape((7, 7, 256)))\n",
        "    assert model.output_shape == (None, 7, 7, 256) # 注意：batch size 没有限制\n",
        "\n",
        "    model.add(layers.Conv2DTranspose(128, (5, 5), strides=(1, 1), padding='same', use_bias=False))\n",
        "    assert model.output_shape == (None, 7, 7, 128)\n",
        "    model.add(layers.BatchNormalization())\n",
        "    model.add(layers.LeakyReLU())\n",
        "\n",
        "    model.add(layers.Conv2DTranspose(64, (5, 5), strides=(2, 2), padding='same', use_bias=False))\n",
        "    assert model.output_shape == (None, 14, 14, 64)\n",
        "    model.add(layers.BatchNormalization())\n",
        "    model.add(layers.LeakyReLU())\n",
        "\n",
        "    model.add(layers.Conv2DTranspose(1, (5, 5), strides=(2, 2), padding='same', use_bias=False, activation='tanh'))\n",
        "    assert model.output_shape == (None, 28, 28, 1)\n",
        "\n",
        "    return model"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "GyWgG09LCSJl"
      },
      "source": [
        "使用（尚未训练的）生成器创建一张图片。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "o6VvUbMqgLaS",
        "colab": {}
      },
      "source": [
        "generator = make_generator_model()\n",
        "\n",
        "noise = tf.random.normal([1, 100])\n",
        "generated_image = generator(noise, training=False)\n",
        "\n",
        "plt.imshow(generated_image[0, :, :, 0], cmap='gray')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "D0IKnaCtg6WE"
      },
      "source": [
        "### 判别器\n",
        "\n",
        "判别器是一个基于 CNN 的图片分类器。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "dw2tPLmk2pEP",
        "colab": {}
      },
      "source": [
        "def make_discriminator_model():\n",
        "    model = tf.keras.Sequential()\n",
        "    model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',\n",
        "                                     input_shape=[28, 28, 1]))\n",
        "    model.add(layers.LeakyReLU())\n",
        "    model.add(layers.Dropout(0.3))\n",
        "\n",
        "    model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))\n",
        "    model.add(layers.LeakyReLU())\n",
        "    model.add(layers.Dropout(0.3))\n",
        "\n",
        "    model.add(layers.Flatten())\n",
        "    model.add(layers.Dense(1))\n",
        "\n",
        "    return model"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "QhPneagzCaQv"
      },
      "source": [
        "使用（尚未训练的）判别器来对图片的真伪进行判断。模型将被训练为为真实图片输出正值，为伪造图片输出负值。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "-nnSVbzhgLaX",
        "colab": {}
      },
      "source": [
        "discriminator = make_discriminator_model()\n",
        "decision = discriminator(generated_image)\n",
        "print (decision)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0FMYgY_mPfTi"
      },
      "source": [
        "## 定义损失函数和优化器\n",
        "\n",
        "为两个模型定义损失函数和优化器。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "psQfmXxYKU3X",
        "colab": {}
      },
      "source": [
        "# 该方法返回计算交叉熵损失的辅助函数\n",
        "cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "PKY_iPSPNWoj"
      },
      "source": [
        "### 判别器损失\n",
        "\n",
        "该方法量化判别器从判断真伪图片的能力。它将判别器对真实图片的预测值与值全为 1 的数组进行对比，将判别器对伪造（生成的）图片的预测值与值全为 0 的数组进行对比。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "wkMNfBWlT-PV",
        "colab": {}
      },
      "source": [
        "def discriminator_loss(real_output, fake_output):\n",
        "    real_loss = cross_entropy(tf.ones_like(real_output), real_output)\n",
        "    fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)\n",
        "    total_loss = real_loss + fake_loss\n",
        "    return total_loss"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Jd-3GCUEiKtv"
      },
      "source": [
        "### 生成器损失\n",
        "\n",
        "生成器损失量化其欺骗判别器的能力。直观来讲，如果生成器表现良好，判别器将会把伪造图片判断为真实图片（或 1）。这里我们将把判别器在生成图片上的判断结果与一个值全为 1 的数组进行对比。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "90BIcCKcDMxz",
        "colab": {}
      },
      "source": [
        "def generator_loss(fake_output):\n",
        "    return cross_entropy(tf.ones_like(fake_output), fake_output)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MgIc7i0th_Iu"
      },
      "source": [
        "由于我们需要分别训练两个网络，判别器和生成器的优化器是不同的。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "iWCn_PVdEJZ7",
        "colab": {}
      },
      "source": [
        "generator_optimizer = tf.keras.optimizers.Adam(1e-4)\n",
        "discriminator_optimizer = tf.keras.optimizers.Adam(1e-4)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "mWtinsGDPJlV"
      },
      "source": [
        "### 保存检查点\n",
        "\n",
        "本笔记还演示了如何保存和恢复模型，这在长时间训练任务被中断的情况下比较有帮助。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "CA1w-7s2POEy",
        "colab": {}
      },
      "source": [
        "checkpoint_dir = './training_checkpoints'\n",
        "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n",
        "checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,\n",
        "                                 discriminator_optimizer=discriminator_optimizer,\n",
        "                                 generator=generator,\n",
        "                                 discriminator=discriminator)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Rw1fkAczTQYh"
      },
      "source": [
        "## 定义训练循环\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "NS2GWywBbAWo",
        "colab": {}
      },
      "source": [
        "EPOCHS = 50\n",
        "noise_dim = 100\n",
        "num_examples_to_generate = 16\n",
        "\n",
        "\n",
        "# 我们将重复使用该种子（因此在动画 GIF 中更容易可视化进度）\n",
        "seed = tf.random.normal([num_examples_to_generate, noise_dim])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "jylSonrqSWfi"
      },
      "source": [
        "训练循环在生成器接收到一个随机种子作为输入时开始。该种子用于生产一张图片。判别器随后被用于区分真实图片（选自训练集）和伪造图片（由生成器生成）。针对这里的每一个模型都计算损失函数，并且计算梯度用于更新生成器与判别器。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "3t5ibNo05jCB",
        "colab": {}
      },
      "source": [
        "# 注意 `tf.function` 的使用\n",
        "# 该注解使函数被“编译”\n",
        "@tf.function\n",
        "def train_step(images):\n",
        "    noise = tf.random.normal([BATCH_SIZE, noise_dim])\n",
        "\n",
        "    with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:\n",
        "      generated_images = generator(noise, training=True)\n",
        "\n",
        "      real_output = discriminator(images, training=True)\n",
        "      fake_output = discriminator(generated_images, training=True)\n",
        "\n",
        "      gen_loss = generator_loss(fake_output)\n",
        "      disc_loss = discriminator_loss(real_output, fake_output)\n",
        "\n",
        "    gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)\n",
        "    gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)\n",
        "\n",
        "    generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))\n",
        "    discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "2M7LmLtGEMQJ",
        "colab": {}
      },
      "source": [
        "def train(dataset, epochs):\n",
        "  for epoch in range(epochs):\n",
        "    start = time.time()\n",
        "\n",
        "    for image_batch in dataset:\n",
        "      train_step(image_batch)\n",
        "\n",
        "    # 继续进行时为 GIF 生成图像\n",
        "    display.clear_output(wait=True)\n",
        "    generate_and_save_images(generator,\n",
        "                             epoch + 1,\n",
        "                             seed)\n",
        "\n",
        "    # 每 15 个 epoch 保存一次模型\n",
        "    if (epoch + 1) % 15 == 0:\n",
        "      checkpoint.save(file_prefix = checkpoint_prefix)\n",
        "\n",
        "    print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))\n",
        "\n",
        "  # 最后一个 epoch 结束后生成图片\n",
        "  display.clear_output(wait=True)\n",
        "  generate_and_save_images(generator,\n",
        "                           epochs,\n",
        "                           seed)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2aFF7Hk3XdeW"
      },
      "source": [
        "**生成与保存图片**\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "RmdVsmvhPxyy",
        "colab": {}
      },
      "source": [
        "def generate_and_save_images(model, epoch, test_input):\n",
        "  # 注意 training` 设定为 False\n",
        "  # 因此，所有层都在推理模式下运行（batchnorm）。\n",
        "  predictions = model(test_input, training=False)\n",
        "\n",
        "  fig = plt.figure(figsize=(4,4))\n",
        "\n",
        "  for i in range(predictions.shape[0]):\n",
        "      plt.subplot(4, 4, i+1)\n",
        "      plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray')\n",
        "      plt.axis('off')\n",
        "\n",
        "  plt.savefig('image_at_epoch_{:04d}.png'.format(epoch))\n",
        "  plt.show()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "dZrd4CdjR-Fp"
      },
      "source": [
        "## 训练模型\n",
        "调用上面定义的 `train()` 方法来同时训练生成器和判别器。注意，训练 GANs 可能是棘手的。重要的是，生成器和判别器不能够互相压制对方（例如，他们以相似的学习率训练）。\n",
        "\n",
        "在训练之初，生成的图片看起来像是随机噪声。随着训练过程的进行，生成的数字将越来越真实。在大概 50 个 epoch 之后，这些图片看起来像是 MNIST 数字。使用 Colab 中的默认设置可能需要大约 1 分钟每 epoch。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Ly3UN0SLLY2l",
        "colab": {}
      },
      "source": [
        "%%time\n",
        "train(train_dataset, EPOCHS)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "rfM4YcPVPkNO"
      },
      "source": [
        "恢复最新的检查点。"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "SKeqh9GlgLa7",
        "colab": {}
      },
      "source": [
        "checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "P4M_vIbUi7c0"
      },
      "source": [
        "## 创建 GIF\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "WfO5wCdclHGL",
        "colab": {}
      },
      "source": [
        "# 使用 epoch 数生成单张图片\n",
        "def display_image(epoch_no):\n",
        "  return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "TsUudzLCgLbA",
        "colab": {}
      },
      "source": [
        "display_image(EPOCHS)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "NywiH3nL8guF"
      },
      "source": [
        "使用训练过程中生成的图片通过 `imageio` 生成动态 gif "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "IGKQgENQ8lEI",
        "colab": {}
      },
      "source": [
        "anim_file = 'dcgan.gif'\n",
        "\n",
        "with imageio.get_writer(anim_file, mode='I') as writer:\n",
        "  filenames = glob.glob('image*.png')\n",
        "  filenames = sorted(filenames)\n",
        "  last = -1\n",
        "  for i,filename in enumerate(filenames):\n",
        "    frame = 2*(i**0.5)\n",
        "    if round(frame) > round(last):\n",
        "      last = frame\n",
        "    else:\n",
        "      continue\n",
        "    image = imageio.imread(filename)\n",
        "    writer.append_data(image)\n",
        "  image = imageio.imread(filename)\n",
        "  writer.append_data(image)\n",
        "\n",
        "import IPython\n",
        "if IPython.version_info > (6,2,0,''):\n",
        "  display.Image(filename=anim_file)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cGhC3-fMWSwl"
      },
      "source": [
        "如果您正在使用 Colab，您可以通过如下代码下载动画："
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "uV0yiKpzNP1b",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  from google.colab import files\n",
        "except ImportError:\n",
        "   pass\n",
        "else:\n",
        "  files.download(anim_file)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "k6qC-SbjK0yW"
      },
      "source": [
        "## 下一步\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "xjjkT9KAK6H7"
      },
      "source": [
        "本教程展示了实现和训练 GAN 模型所需的全部必要代码。接下来，您可能想尝试其他数据集，例如大规模名人面部属性（CelebA）数据集 [在 Kaggle 上获取](https://www.kaggle.com/jessicali9530/celeba-dataset/home)。要了解更多关于 GANs 的信息，我们推荐参阅 [NIPS 2016 教程： 生成对抗网络](https://arxiv.org/abs/1701.00160)。"
      ]
    }
  ]
}